package com.destroyer.will.ability.impl.auth;

import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson.JSON;
import com.destroyer.common.constant.DicConstant;
import com.destroyer.common.entity.auth.AuthBaseVO;
import com.destroyer.common.entity.auth.AuthStudentVO;
import com.destroyer.common.entity.system.ResultEnum;
import com.destroyer.common.exception.ServiceException;
import com.destroyer.common.util.DateUtils;
import com.destroyer.common.util.Func;
import com.destroyer.core.entity.exmStudent.bo.ExmStudentBO;
import com.destroyer.core.entity.exmStudent.bo.ExmStudentQueryBO;
import com.destroyer.core.entity.exmStudent.vo.ExmStudentVO;
import com.destroyer.core.entity.wechat.bo.WechatUserCodeBO;
import com.destroyer.core.entity.wechat.vo.WechatUserAuthVO;
import com.destroyer.core.service.wechat.IWechatFeignService;
import com.destroyer.will.ability.auth.IAuthStudentWechatLoginAbilityService;
import com.destroyer.will.service.exmStudent.IExmStudentCreateService;
import com.destroyer.will.service.exmStudent.IExmStudentGetListService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 标题：AuthStudentWechatLoginAbilityServiceImpl
 * 说明：
 * 时间：2024/3/5
 * 作者：admin
 */
@Service
public class AuthStudentWechatLoginAbilityServiceImpl implements IAuthStudentWechatLoginAbilityService {

    @Autowired
    private IWechatFeignService wechatFeignService;

    @Autowired
    private IExmStudentGetListService studentGetListService;

    @Autowired
    private IExmStudentCreateService studentCreateService;

    /**
     * JWT KEY
     */
    @Value("${jwt-key}")
    private String jwtKey;

    /**
     * 过期时间
     */
    @Value("${access-token-expires}")
    private Integer accessTokenExpires;


    /**
     * 学生用户登录
     *
     * @param req
     * @return
     */
    @Override
    @Transactional
    public AuthBaseVO<AuthStudentVO> login(WechatUserCodeBO req) {
        AuthBaseVO<AuthStudentVO> rsp = new AuthBaseVO<>();
        //入参效验
        this.validParams(req);
        //执行核心逻辑前调用
        this.beforeToDo(req);
        WechatUserAuthVO wechatUserAuthVO = wechatFeignService.getUserOpenIdByCode(req);
        String openId = wechatUserAuthVO.getOpenid();
        if(Func.isEmpty(openId)){
            throw new ServiceException(ResultEnum.FAILURE, "获取用户OpenID为空！");

        }
        ExmStudentQueryBO exmStudentQueryBO = new ExmStudentQueryBO();
        exmStudentQueryBO.setWxopenid(openId);
        List<ExmStudentVO> studentVOList = studentGetListService.getList(exmStudentQueryBO);
        if (studentVOList.size() == 0) {
           this.autoRegister(wechatUserAuthVO);
        }
        studentVOList = studentGetListService.getList(exmStudentQueryBO);
        if (studentVOList.size() == 0) {
            throw new ServiceException(ResultEnum.FAILURE, "用户数据异常，当前用户不存在！");

        }
        if (studentVOList.size() > 1) {
            throw new ServiceException(ResultEnum.FAILURE, "用户数据异常，存在多个用户！");
        }
        ExmStudentVO exmStudentVO = studentVOList.get(0);
        AuthStudentVO authStudentVO = new AuthStudentVO();
        BeanUtils.copyProperties(exmStudentVO, authStudentVO);
        authStudentVO.setSessionKey(wechatUserAuthVO.getSessionKey());
        rsp.setAuth(authStudentVO);
        this.buildRsp(rsp);
        return rsp;
    }

    /**
     * 构造出参
     *
     * @param authBaseVO
     */
    private void buildRsp(AuthBaseVO<AuthStudentVO> authBaseVO) {
        Date currentDateYYYYMMDDHHMMSS = DateUtils.getCurrentDateYYYYMMDDHHMMSS();
        authBaseVO.setLoginTime(currentDateYYYYMMDDHHMMSS);
        authBaseVO.setSysRole(DicConstant.SYS_ROLE.STU_USER);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentDateYYYYMMDDHHMMSS);
        calendar.add(Calendar.SECOND, accessTokenExpires);
        authBaseVO.setExpireTime(calendar.getTime());
        Map map = JSON.parseObject(JSON.toJSONString(authBaseVO), Map.class);
        String token = JWTUtil.createToken(map, this.jwtKey.getBytes());
        authBaseVO.setToken(token);

    }


    /**
     * 类通用入参校验
     *
     * @param req
     */
    private void validParams(WechatUserCodeBO req) {
        if (null == req) {
            throw new ServiceException(ResultEnum.PARAM_MISS, "入参不能为空");
        } else {
            if (Func.isEmpty(req.getCode())) {
                throw new ServiceException(ResultEnum.PARAM_MISS, "入参code不能为空");

            }
        }
    }

    /**
     * 类通用执行前调用逻辑
     *
     * @param req 入参
     */
    private void beforeToDo(WechatUserCodeBO req) {
        // TODO 执行前调用逻辑

    }


    /**
     * 微信自动注册
     * @param req ID
     * @return
     */
    private void autoRegister(WechatUserAuthVO req) {
        ExmStudentBO exmStudentBO = new ExmStudentBO();
        exmStudentBO.setWxopenid(req.getOpenid());
        exmStudentBO.setWxunid(req.getUnionid());
        exmStudentBO.setIsvip(false);
        studentCreateService.create(exmStudentBO);
    }
}
